from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.http import Http404


class Category(models.Model):
	name = models.CharField(max_length = 200)

	def __unicode__(self):
		return self.name
	
class Item(models.Model):
	name = models.CharField(max_length = 200)

	def __unicode__(self):
		return self.name

	  
class Recipie(models.Model):
	name = models.CharField(max_length = 200)
	user = models.ForeignKey(User) 
	categories = models.ManyToManyField(Category)
	items = models.ManyToManyField(Item)
	description = models.TextField()
	
	def __unicode__(self):
		return self.name
	
	class Meta:
		'''
		Model specific options
		'''
		ordering = ['name']


class RecipieSearchForm(ModelForm):
	class Meta:
		model = Recipie
		fields = ['items']

def delete_recipie(id):
	try:
		r = Recipie.objects.get(id = id)
		r.delete()
	except Recipie.DoesNotExist:
		raise Http404

def create_category(name):
	try:
		newCategory = Category(name=name)
		newCategory.save()
	except ValueError:
		raise Http404

def delete_category(id) :
	try :
		r = Category.objects.get(id = id)
		r.delete()
	except Category.DoesNotExist :
		raise Http404

def create_recepie(name, categories, items, description):
	try:
		recept = Recipie()
		recept.name = name
		recept.description = description
		#todo user
		recept.user_id = 1

		recept.save()
	
		for category in categories:
			r = Category.objects.get(id = category)
			recept.categories.add(r)
		for item in items:
			r = Item.objects.get(id = item)
			recept.items.add(r)

	except ValueError:
		raise Http404

def update_recepie(id, name, categories, items, description):
	try:
		recept = Recipie.objects.get(id = id)
		recept.name = name
		recept.description = description
		recept.save()
		recept.categories.clear()
		for category in categories:
			r = Category.objects.get(id = category)
			recept.categories.add(r)
		recept.items.clear()
		for item in items:
			r = Item.objects.get(id = item)
			recept.items.add(r)
	except Recipie.DoesNotExist:
		raise Http404
	
def create_item(name):
	try:
		stavak = Item(name=name)
		stavak.save()
	except ValueError:
		raise Http404
	
def delete_item(id):
	try:
		r = Item.objects.get(id = id)
        	r.delete()
	except Item.DoesNotExist:
		raise Http404

def update_item(id, name):
	try:
		stavak = Item.objects.get(id = id)
		stavak.name = name
		stavak.save()
	except Item.DoesNotExist:
		raise Http404
